<template>
  <div :id="viewerId" class="ld-viewer-container">
    <slot></slot>
  </div>
</template>

<script type="text/babel">
import events from '../../mixins/events'

export default {
  name: 'LdViewer',
  mixins: [events],
  props: {
    viewerId: {
      type: String,
      required: true,
    },
    options: {
      type: Object,
      default: function () {
        return {}
      },
    },
  },
  data() {
    return {
      viewer: null,
    }
  },
  watch: {
    options: {
      handler(newVal, oldVal) {
        this.$viewer && this.$viewer.setOptions(newVal)
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    initViewer() {
      this.viewer = new Cesium.Viewer(this.viewerId, this.options)
      this.$children.forEach((component) => {
        component.$emit('on-viewer-ready', this.viewer)
      })
      window.Viewer = window.Viewer = this.viewer
      this.$emit('on-viewer-created', this.viewer)
    },
  },
  created() {},
  mounted() {
    this.initViewer()
  },
  beforeDestroy() {
    if (this.viewer && !this.viewer.isDestroyed()) {
      this.viewer.destroy()
    }
  },
}
</script>
<style>
.ld-viewer-container {
  height: 100%;
  width: 100%;
  position: absolute;
}
</style>
